#include <errno.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>

//共享内存中存储的数据
union val_t {
    int b_val;    //bool类型存储空间1
    int i_val;    //整形值存储空间2
    float f_val;  //浮点值存储空间3
};
//消息队列发送的数据
struct msgbuf {
    long mtype;
    int key;
    union val_t val;
};

int main(int argc, char const *argv[]) {
    //创建key
    key_t key = ftok("/tmp/ipc/msg/msg", 'j');
    if (key < 0) {
        perror("queue ftok err");

        return -1;
    }

    //创建消息队列
    int msgid = msgget(key, IPC_CREAT | IPC_EXCL | 0666);
    if (msgid < 0) {
        if (errno == EEXIST) {
            msgid = msgget(key, 0666);
        } else {
            perror("msgget err");
            return -1;
        }
    }
    printf("msgid:%d\n", msgid);
    struct msgbuf buf;

    msgrcv(msgid, &buf, sizeof(struct msgbuf) - sizeof(long), 1l, 0);
    printf("%d:%d\n", buf.key, buf.val.b_val);
    return 0;
}
